package com.yycx.module.bus.provider.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yycx.common.base.entity.EntityMap;
import com.yycx.common.constants.CommonConstants;
import com.yycx.common.mybatis.base.service.impl.BaseServiceImpl;
import com.yycx.common.mybatis.model.ResultBody;
import com.yycx.common.mybatis.query.CriteriaQuery;
import com.yycx.common.mybatis.query.CriteriaSave;
import com.yycx.common.mybatis.query.CriteriaUpdate;
import com.yycx.common.security.OpenHelper;
import com.yycx.module.bus.client.entity.BusInvoiceunit;
import com.yycx.module.bus.client.entity.hy.BusInvoiceunitQuota;
import com.yycx.module.bus.provider.mapper.BusInvoiceunitMapper;
import com.yycx.module.bus.provider.service.BusInvoiceunitQuotaService;
import com.yycx.module.bus.provider.service.BusInvoiceunitService;
import com.yycx.module.system.client.entity.SysCompany;
import com.yycx.module.system.client.entity.SysOrganization;
import com.yycx.module.system.provider.service.SysCompanyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 开票单位接口实现类
 *
 * @author flyme
 * @date 2020-08-02
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class BusInvoiceunitServiceImpl extends BaseServiceImpl<BusInvoiceunitMapper, BusInvoiceunit> implements BusInvoiceunitService {

    @Autowired
    private SysCompanyService companyService;

    @Autowired
    private BusInvoiceunitQuotaService busInvoiceunitQuotaService;


    @Override
    public ResultBody beforeAdd(CriteriaSave cs, BusInvoiceunit invoiceunit, EntityMap extra) {
        Long companyId = OpenHelper.getCompanyId();
        SysCompany company = companyService.getById(companyId);
        Long organizationId = company.getOrganizationId();
        invoiceunit.setCompanyId(companyId);
        invoiceunit.setOrganizationId(organizationId);
        invoiceunit.setInvoiceunitState(CommonConstants.ENABLED);
        return ResultBody.ok();
    }

    @Override
    @Transactional
    public ResultBody afterAdd(CriteriaSave cs, BusInvoiceunit busInvoiceunit, EntityMap extra) {

        if (busInvoiceunit.getMonthQuota().compareTo(new BigDecimal(0)) > 0) {
            //月额度大于剩余额度 直接用剩余
            /*if (busInvoiceunit.getResidueQuota().compareTo(busInvoiceunit.getMonthQuota()) == -1) {
                busInvoiceunit.setMonthQuota(busInvoiceunit.getResidueQuota());
            }*/
            BusInvoiceunitQuota quota = BusInvoiceunitQuota.builder().invoiceUnitId(busInvoiceunit.getInvoiceUnitId()).quotaYear(DateUtil.thisYear()).quotaMonth(DateUtil.thisMonth() + "").totalQuota(busInvoiceunit.getMonthQuota()).maxQuota(busInvoiceunit.getMonthQuota()).build();
            busInvoiceunitQuotaService.saveOrUpdate(quota);
        }
        return super.afterAdd(cs, busInvoiceunit, extra);
    }

    @Override
    @Transactional
    public ResultBody afterEdit(CriteriaUpdate cu, BusInvoiceunit busInvoiceunit, EntityMap extra) {
        if (busInvoiceunit.getMonthQuota().compareTo(new BigDecimal(0)) > 0) {
            //月额度大于剩余额度 直接用剩余
            /*if (busInvoiceunit.getResidueQuota().compareTo(busInvoiceunit.getMonthQuota()) == -1) {
                busInvoiceunit.setMonthQuota(busInvoiceunit.getResidueQuota());
            }*/
            BusInvoiceunitQuota one = busInvoiceunitQuotaService.getOne(new QueryWrapper<BusInvoiceunitQuota>().lambda().eq(BusInvoiceunitQuota::getInvoiceUnitId, busInvoiceunit.getInvoiceUnitId()).eq(BusInvoiceunitQuota::getQuotaYear, DateUtil.thisYear()).eq(BusInvoiceunitQuota::getQuotaMonth, DateUtil.thisMonth()));
            if (null != one) {
                one.setTotalQuota(busInvoiceunit.getMonthQuota()).setMaxQuota(busInvoiceunit.getMonthQuota());
            } else {
                one = BusInvoiceunitQuota.builder().invoiceUnitId(busInvoiceunit.getInvoiceUnitId()).quotaYear(DateUtil.thisYear()).quotaMonth(DateUtil.thisMonth() + "").totalQuota(busInvoiceunit.getMonthQuota()).maxQuota(busInvoiceunit.getMonthQuota()).build();
            }
            busInvoiceunitQuotaService.saveOrUpdate(one);
        }

        return super.afterEdit(cu, busInvoiceunit, extra);
    }

    @Override
    public ResultBody beforeListEntityMap(CriteriaQuery<BusInvoiceunit> cq, BusInvoiceunit busInvoiceunit, EntityMap requestMap) {
        Long companyId = OpenHelper.getCompanyId();
        cq.eq(BusInvoiceunit.class, "companyId", companyId);
        cq.eq(BusInvoiceunit.class, "invoiceunitState", CommonConstants.ENABLED);
        return super.beforeListEntityMap(cq, busInvoiceunit, requestMap);
    }

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public ResultBody beforePageList(CriteriaQuery<BusInvoiceunit> cq, BusInvoiceunit invoiceunit, EntityMap requestMap) {
        Long companyId = OpenHelper.getCompanyId();
        if (companyId.equals(1018L)) {
            companyId = 5L;
        }
        cq.select(BusInvoiceunit.class, "*");
        cq.select(SysCompany.class, "companyName");
        cq.select(SysOrganization.class, "organizationName");
        cq.like(BusInvoiceunit.class, "invoiceunitName");
        cq.eq(BusInvoiceunit.class, "linkMan");
        cq.eq(BusInvoiceunit.class, "organizationId");
        cq.eq(BusInvoiceunit.class, "companyId", companyId);
        cq.eq(BusInvoiceunit.class, "legalPerson");
        cq.orderByDesc("invoiceunit.createTime");
        cq.createJoin(SysOrganization.class);
        cq.createJoin(SysCompany.class);
        return ResultBody.ok();
    }

    @Override
    public List<EntityMap> afterPageList(CriteriaQuery<BusInvoiceunit> cq, List<EntityMap> data, ResultBody resultBody) {

        for (EntityMap datum : data) {
            if (datum.getBigDecimal("monthQuota").compareTo(new BigDecimal(0)) > 0) {

                List<BusInvoiceunitQuota> monthQuota = busInvoiceunitQuotaService.getYearQuotaBy(datum.getLong("invoiceUnitId"), 0, null);
                if (CollUtil.isNotEmpty(monthQuota)) {
                    double yearQuota = monthQuota.stream().filter(a -> a.getQuotaYear().intValue() == DateUtil.thisYear()).mapToDouble(a -> a.getUseQuota().doubleValue()).sum();
                    datum.put("yearQuota", yearQuota);

                    double useQuota = monthQuota.stream().mapToDouble(a -> a.getUseQuota().doubleValue()).sum();
                    datum.put("useQuota", useQuota);


                }
            }
        }

        return data;
    }

    @Override
    public ResultBody setMonthQuota(Map params) {

        List<String> ids = StrUtil.split(params.get("ids").toString(), ',');


        List<BusInvoiceunit> busInvoiceunits = this.listByIds(ids);
        for (BusInvoiceunit busInvoiceunit : busInvoiceunits) {
            if (busInvoiceunit.getResidueQuota().compareTo(new BigDecimal(params.get("monthQuota").toString())) > 0) {
                busInvoiceunit.setMonthQuota(new BigDecimal(params.get("monthQuota").toString()));
            } else {
                busInvoiceunit.setMonthQuota(busInvoiceunit.getResidueQuota());
            }
        }
        this.saveOrUpdateBatch(busInvoiceunits);

        List<BusInvoiceunitQuota> list = new ArrayList<>();

        for (BusInvoiceunit busInvoiceunit : busInvoiceunits) {

            List<BusInvoiceunitQuota> yearQuotaBy = busInvoiceunitQuotaService.getYearQuotaBy(busInvoiceunit.getInvoiceUnitId(), DateUtil.thisYear(), DateUtil.thisMonth() + "");
            if (CollUtil.isNotEmpty(yearQuotaBy)) {
                BusInvoiceunitQuota busInvoiceunitQuota = yearQuotaBy.get(0);
                busInvoiceunitQuota.setTotalQuota(busInvoiceunit.getMonthQuota());
                busInvoiceunitQuota.setMaxQuota(busInvoiceunit.getMonthQuota());
                list.add(busInvoiceunitQuota);
            } else {
                BusInvoiceunitQuota quota = BusInvoiceunitQuota.builder().invoiceUnitId(busInvoiceunit.getInvoiceUnitId()).quotaYear(DateUtil.thisYear()).quotaMonth(DateUtil.thisMonth() + "").totalQuota(busInvoiceunit.getMonthQuota()).maxQuota(busInvoiceunit.getMonthQuota()).build();
                list.add(quota);
            }
        }
        return ResultBody.ok(busInvoiceunitQuotaService.saveOrUpdateBatch(list));
    }


}
